class Host < ActiveRecord::Base
  attr_accessible :description, :ip, :name
  has_many :oids, :dependent => :destroy
  PORT=161

  def process_name
    "#{ip}_torrents"
  end

  def torrents_active?
    `ps aux | grep #{process_name} | grep -v grep` != ""
  end

  def torrents_activate
    pid = fork do
      puts "./script/snmp_bulk.rb #{ip} 30"
      exec "./script/snmp_bulk.rb #{ip} 30"
    end
    Process.detach(pid)
  end

  def torrents_deactivate
    %x(kill -9 `ps aux | grep #{process_name} | grep -v grep | cut -d' ' -f3`)
  end

  def get_max_upload
    begin
    `snmpget -c public -v2c #{ip}:#{PORT} 1.3.6.1.4.1.12619.1.2.1.0`.split[3].delete('"')
    rescue
      "unknown"
    end
  end
  
  def get_max_download
    begin
    `snmpget -c public -v2c #{ip}:#{PORT} 1.3.6.1.4.1.12619.1.2.2.0`.split[3].delete('"')
    rescue
      "unknown"
    end
  end

  def get_max_active
    begin
    `snmpget -c public -v2c #{ip}:#{PORT} 1.3.6.1.4.1.12619.1.2.3.0`.split[3].delete('"')
    rescue
      "unknown"
    end
  end

  def get_a
    begin
    `snmpget -c public -v2c #{ip}:#{PORT} 1.3.6.1.4.1.12619.1.2.4.0`.split[3].delete('"')
    rescue
      "unknown"
    end
  end

  def get_b
    begin
    `snmpget -c public -v2c #{ip}:#{PORT} 1.3.6.1.4.1.12619.1.2.5.0`.split[3].delete('"')
    rescue
      "unknown"
    end
  end

  def set_max_upload(val)
    `snmpset -c public -v2c #{ip}:#{PORT} 1.3.6.1.4.1.12619.1.2.1.0 s "#{val}"`
  end
  
  def set_max_download(val)
    `snmpset -c public -v2c #{ip}:#{PORT} 1.3.6.1.4.1.12619.1.2.2.0 s "#{val}"`
  end

  def set_max_active(val)
    `snmpset -c public -v2c #{ip}:#{PORT} 1.3.6.1.4.1.12619.1.2.3.0 s "#{val}"`
  end

  def set_a(val)
    `snmpset -c public -v2c #{ip}:#{PORT} 1.3.6.1.4.1.12619.1.2.4.0 s "#{val}"`
  end

  def set_b(val)
    `snmpset -c public -v2c #{ip}:#{PORT} 1.3.6.1.4.1.12619.1.2.5.0 s "#{val}"`
  end

  def torrent_status_text(status)
    status = status.to_i
    if status == 0
      "Stopped"
    elsif status == 1
      "Starting"
    elsif status == 2
      "Checking files"
    elsif status <= 4
      "Checking files - will start soon"
    elsif status <= 8
      "Verifying"
    elsif status <= 16
      "Error"
    elsif status <= 32
      "Paused"
    elsif status <= 64
      "Queued"
    elsif status <= 128
      "Finished"
    end
  end


  def torrent_names
    ret = []
    files = Dir.glob("rrd_data/#{ip}*")
    files = files.find_all{|f| f =~ /rrd_data\/#{ip}.*/}
    p ip
    p files
    files.each do |file|
      File.open file, "r" do |fh|
        ret << fh.read
      end
    end
    ret
  end

  def graph_for(torrent_name, name, rrd_path)
    img_name = rrd_path.gsub(/rrd_data/, "app/assets/images/rrd").gsub(/rrd$/, "png")
    if File.exists? rrd_path
      RRD.graph(
        img_name,
        "--title", "#{self.name} - #{torrent_name} - #{name}",
        "--interlace",
        "--imgformat", "PNG",
        "--width=450",
        "DEF:a=#{rrd_path}:a:AVERAGE",
        "CDEF:line=TIME,2400,%,300,LT,a,UNKN,IF",
        "AREA:a#00b6e4:alpha",
        "LINE3:line#ff0000")
    end
    img_name.gsub(/app\/assets\/images\//, "")
  end

  def torrents
    ret = []
    names = torrent_names
    names.each do |name|
      begin
        ret << {
          name: name.delete('"'),
          status: torrent_status_text(File.open("rrd_data/#{ip}_#{name}_Status.txt").read),
          size: File.open("rrd_data/#{ip}_#{name}_Size.txt").read,
          graphs: {
            percent: graph_for(name.delete('"'), 'percent', "rrd_data/#{ip}_#{name}_Percent.rrd"),
            total_downloaded: graph_for(name.delete('"'), 'total downloaded', "rrd_data/#{ip}_#{name}_Total_Downloaded.rrd"),
            total_uploaded: graph_for(name.delete('"'), 'total uploaded', "rrd_data/#{ip}_#{name}_Total_Uploaded.rrd"),
            upload_speed: graph_for(name.delete('"'), 'upload speed', "rrd_data/#{ip}_#{name}_Upload_speed.rrd"),
            download_speed: graph_for(name.delete('"'), 'download speed', "rrd_data/#{ip}_#{name}_Download_speed.rrd"),
            peers: graph_for(name.delete('"'), 'peers', "rrd_data/#{ip}_#{name}_Peers.rrd"),
            seeds: graph_for(name.delete('"'), 'seeds', "rrd_data/#{ip}_#{name}_Seeds.rrd")
          }
        }
      rescue => e
        # Ignores a torrent that don't have all files
        logger.debug e
      end
    end
    ret
  end
end
